package com.inspur.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 文件下载类
 * @author  zhangteng 
 * @date 创建时间：2017年7月18日 
 */
public class FilisDownLoad extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	  private static final String FILE_DIRE_PATH = "/upload/";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FilisDownLoad() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String filepath = request.getParameter("filepath");
		
		String filename = System.currentTimeMillis() + filepath.substring(filepath.lastIndexOf("."));
		
		 
        String realPath = getServletContext().getRealPath("/");
		String filePath =realPath +".."+ filepath; 
		File file = new File(filePath);
		if(!file.exists()){
			file.createNewFile();
		}
		FileInputStream fis = new FileInputStream(file);
		filename = new  String(filename.getBytes("gb2312"),"iso8859-1");
        response.setHeader("Content-disposition", (new StringBuilder()).append("attachment; filename=").append(filename).toString());
		response.setContentType("application/x-download");
		OutputStream out = response.getOutputStream();
		byte[] b = new byte[1024];
		int len;
		while ((len = fis.read(b)) > 0)
			out.write(b, 0, len);
		out.flush();
		out.close();
		fis.close();
	}

}
